#include "stm32f10x.h"              
extern uint8_t TDS[6];
uint8_t Start[] = {0xA0,0x00,0x00,0x00,0x00,0xA0};
uint8_t Adjust[] = {0xA6,0x00,0x00,0x00,0x00,0xA6};
uint8_t TDS_flag = 0;
void TDS_Init(void) 
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;//配置输出TX-PA9
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//配置输入RX-PA10
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	USART_InitTypeDef USART_InitStructure;//配置USART1
	USART_InitStructure.USART_BaudRate = 9600;//波特率
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
													//不使用流控
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;//发送和接收模式
	USART_InitStructure.USART_Parity = USART_Parity_No;//无校验位
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//停止位1位
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;//数据位8位
	USART_Init (USART1,&USART_InitStructure);
	
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//开启接收中断
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);		//分组2
	
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel =USART1_IRQn;		//指定通道USART1
	NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;			//通道使能开启
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=2;//抢占优先级设置，分组2取值0，1，2，3.
	NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;		//响应优先级设置，分组2取值0，1，2，3.
	NVIC_Init(&NVIC_InitStruct);
	
	USART_Cmd (USART1,ENABLE);//开启USART1
}

void Send_B(uint8_t B)//发送一个字节
{
	USART_SendData(USART1,B);//发送字节B
	while (USART_GetFlagStatus(USART1, USART_FLAG_TXE)== RESET);
								//等待发送标志位1
}

void Send_Start(void)//发送开始检测信号
{
	uint8_t i;
	for (i = 0 ; i < 6 ; i++)
	{
		Send_B(Start[i]);
	}
}

void Send_Adjust(void)//发送校准清零信号
{
	uint8_t i;
	for (i = 0 ; i < 6 ; i++)
	{
		Send_B(Adjust[i]);
	}
}

void USART1_IRQHandler(void)
{
	if(USART_GetITStatus(USART1, USART_IT_RXNE) == SET)
	{
		TDS[TDS_flag] = USART_ReceiveData(USART1);
		TDS_flag++;
		if (TDS_flag == 6) TDS_flag = 0;
		USART_ClearITPendingBit(USART1, USART_IT_RXNE);
	}
}
